﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Interop;
using System.Threading;

namespace JustPlus
{
    /// <summary>
    /// PlayerPanel.xaml 的交互逻辑
    /// </summary>
    public partial class PlayerPanel : UserControl
    {
        private float sopacity = 0.6f;
        public static Brush bkbrush;//存放stackpanel的背景，当鼠标移入菜单项的时候，需要此背景！
        public static double volum;//存放音量值 
        private Image[] ImageCell;
        private DispatcherTimer tm = new DispatcherTimer();
        private DispatcherTimer labeltm = new DispatcherTimer();
        public GetSongList getsong = new GetSongList();
        public PlayerPanel()
        {
            InitializeComponent();
            ImageCell = new Image[12] { image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11, image12 };
            SetOpacity(0.0f);

            //根据设置项设置以下参数
            slider1.Value = Properties.Settings.Default.DefaultVolume;
            if (Properties.Settings.Default.RememberChannel)
            {
                if (Properties.Settings.Default.CloseChannel != null && Properties.Settings.Default.CloseChannel.cate != 2)
                {
                    GetSongList.currentchannel = Properties.Settings.Default.CloseChannel;
                    GetSongList.lastchannel = null;
                }
            }
            /*getsong.NextCompleted += new GetSongList.NextCompletedEventHandler(NextCompleted);
            getsong.FailLoaded += new GetSongList.FailLoadedEventHandler(FailLoaded);
            getsong.Next(false);*/
            UI_Loaded();
            //this.Loaded += new RoutedEventHandler(UI_Loaded);
            /*Dispatcher.BeginInvoke(new Action(() =>
                {
                    Ele_PreLoad();
                }));*/
        }

        //线程后台进行歌曲加载...
        //private void UI_Loaded(object sender, RoutedEventArgs e)
        private void UI_Loaded()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    getsong.NextCompleted += new GetSongList.NextCompletedEventHandler(NextCompleted);
                    getsong.FailLoaded += new GetSongList.FailLoadedEventHandler(FailLoaded);
                }));
                getsong.Next(true);

            }));
        }

        //获取到歌曲后设置UI界面
        private void NextCompleted(object sender, Song currentsong)
        {
            //Ele_Loaded();
            Dispatcher.BeginInvoke(new Action(() =>
            {
                label6.Opacity = 0;

                label1.Content = currentsong.artist;
                label2.Content = @"<" + currentsong.albumtitle + @">" + " " + currentsong.public_time;
                label3.Content = currentsong.title;

                if (currentsong.like == "1")
                {
                    image6.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/like.png", UriKind.Relative));
                    image6.Tag = @"like.png";
                    if(image6.IsEnabled)
                        image6.ToolTip = "不喜欢";
                }
                else
                {
                    image6.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/favourite.png", UriKind.Relative));
                    image6.Tag = @"favourite.png";
                    if (image6.IsEnabled)
                        image6.ToolTip = "喜欢";
                }
                MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
                mwnd.stackPanel2.Background = new ImageBrush(new BitmapImage(new Uri(currentsong.picture.Replace(@"mpic", @"lpic"), UriKind.Absolute)));
                bkbrush = mwnd.stackPanel2.Background;

                mediaElement1.Source = new Uri(currentsong.url, UriKind.Absolute);
                mediaElement1.Play();
            }));

        }

        private void FailLoaded()
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                label6.Opacity = 1.0;
                label6.Content = @"加载失败，请检查网络或者点击频道重试！";
                //启动定时器，5秒钟后label6消失
                labeltm.Tick += new EventHandler(labeltm_Tick);
                labeltm.Interval = TimeSpan.FromSeconds(5);
                labeltm.Start();
            }));
        }

        private void labeltm_Tick(object sender, EventArgs e)
        {
            label6.Opacity = 0;
            labeltm.Stop();
        }

        //歌曲加载完毕之前，按钮不能使用
        private void Ele_PreLoad()
        {
            for (int i = 3; i <= 11; i++)
            {
                ImageCell[i].IsEnabled = false;
            }
            slider1.IsEnabled = false;
        }

        private void Ele_Loaded()
        {
            for (int i = 3; i <= 11; i++)
            {
                ImageCell[i].IsEnabled = true;
            }
            slider1.IsEnabled = true;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (Image image in ImageCell)
            {
                image.MouseEnter += new MouseEventHandler(Elem_MouseEnter);
                image.MouseLeave += new MouseEventHandler(Elem_MouseLeave);
            }
            if (LoginPanel.HasLoginOn)
            {
                image6.IsEnabled = true;
                //image6.ToolTip = "喜欢";
            }
            else
            {
                image6.IsEnabled = false;
                image6.ToolTip = "请先登录！";
            }
            if (GetSongList.currentchannel.cate != 2)
            {
                image7.IsEnabled = false;
                image7.ToolTip = "仅私人频道可用！";
            }
            else
            {
                image7.IsEnabled = true;
                image7.ToolTip = "不再播放";
            }
        }

        private void Elem_MouseEnter(object sender, MouseEventArgs e)
        {
            Image image = sender as Image;
            image.Opacity = 1.0f;
        }

        private void Elem_MouseLeave(object sender, MouseEventArgs e)
        {
            Image image = sender as Image;
            image.Opacity = sopacity;
        }

        public void SetOpacity(float opacity)
        {
            foreach (Image image in ImageCell)
                image.Opacity = opacity;
            slider1.Opacity = opacity;
        }

        private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            SetOpacity(sopacity);
        }

        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            SetOpacity(0.0f);
        }

        //关闭
        private void image3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
                Application.Current.Shutdown();
        }

        //最小化
        private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow mainwnd = (MainWindow)Application.Current.MainWindow;
            mainwnd.WindowState = WindowState.Minimized;
        }

        //开始播放歌曲
        private void mediaElement1_MediaOpened(object sender, RoutedEventArgs e)
        {
            //progressBar1.Opacity = 1.0;
            image4.ToolTip = @"暂停";

            tm.Tick += new EventHandler(tm_Tick);
            tm.Interval = TimeSpan.FromSeconds(1);
            tm.Start();
        }

        private void tm_Tick(object sender, EventArgs e)
        {
            if (!mediaElement1.NaturalDuration.HasTimeSpan)
            {
                label4.Content = "0:0/0:0";
                return;
            }
            TimeSpan TotalSpan = mediaElement1.NaturalDuration.TimeSpan;
            string totalspan = TotalSpan.Minutes.ToString() + ":" + TotalSpan.Seconds.ToString();
            TimeSpan AfterSpan = mediaElement1.Position;
            label4.Content = AfterSpan.Minutes.ToString() + ":" + AfterSpan.Seconds.ToString() + @"/" + totalspan;
            //TimeSpan LeftTimeSpan = TotalSpan - AfterSpan;
            /*if (LeftTimeSpan.Minutes + LeftTimeSpan.Seconds < 0)
            {
                api.Next(false);
                return;
            }*/
            progressBar1.Value = mediaElement1.Position.TotalSeconds / mediaElement1.NaturalDuration.TimeSpan.TotalSeconds * 100;
        }

        //一首歌歌曲，需要加载下一首
        private void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
        {
            //progressBar1.Opacity = 0;
            label4.Content = "加载中...";
            progressBar1.Value = 0;
            tm.Stop();
            getsong.Next(false);
        }

        //暂停
        private void image4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //image4.ToolTip = @"播放";
            if ((string)image4.Tag == @"pause.png")
            {
                image4.Tag = @"play.png";
                image4.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/play.png", UriKind.Relative));
                image4.ToolTip = @"播放";
                mediaElement1.Pause();
            }
            else if ((string)image4.Tag == @"play.png")
            {
                image4.Tag = @"pause.png";
                image4.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/pause.png", UriKind.Relative));
                image4.ToolTip = @"暂停";
                mediaElement1.Play();
            }
        }

        //跳过该曲
        private void image5_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            label4.Content = "加载中...";
            progressBar1.Value = 0;
            tm.Stop();
            getsong.Next(false);
        }

        //改变音量
        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            //slide控件加载的时候会调用此函数，此时的mediaelement1可能为加载，为null
            if (mediaElement1 == null)
                return;
            mediaElement1.Volume = slider1.Value / 10;
            if (slider1.Value < 0.01)
                mediaElement1.Tag = @"volume0.png";
            else if (slider1.Value < 3)
                mediaElement1.Tag = @"volume1.png";
            else if (slider1.Value < 6.5)
                mediaElement1.Tag = @"volume2.png";
            else
                mediaElement1.Tag = @"volume3.png";
            image9.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/" + mediaElement1.Tag, UriKind.Relative));
        }

        //静音--恢复音量
        private void image9_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (slider1.Value > 0.01)
            {
                volum = slider1.Value;
                slider1.Value = 0;
            }
            else
            {
                slider1.Value = volum;
            }
        }

        //喜欢
        private void image6_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (image6.Tag.ToString() == @"favourite.png")
            {
                image6.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/like.png", UriKind.Relative));
                image6.Tag = @"like.png";
                getsong.Like(true);
            }
            else if (image6.Tag.ToString() == @"like.png")
            {
                image6.Source = new BitmapImage(new Uri(@"/JustPlus;component/Images/favourite.png", UriKind.Relative));
                image6.Tag = @"favourite.png";
                getsong.Like(false);
            }
        }

        private void image6_MouseEnter(object sender, MouseEventArgs e)
        {
            if (image6.IsEnabled && image6.Tag.ToString() == @"like.png")
                image6.ToolTip = "不喜欢";
            else if (image6.IsEnabled && image6.Tag.ToString() == @"favourite.png")
                image6.ToolTip = @"喜欢";
            else if(!image6.IsEnabled)
                image6.ToolTip = @"请先登录！";
        }
    }
}
